package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"net/http"
	"os"

	_ "github.com/go-sql-driver/mysql"
)

type UserInfo struct {
	Username string `form:"username"`
	Password string `form:"password"`
}

// use logrus in gin  //全局变量的目的是所有文件都能够使用
var log = logrus.New()

func initLogrus() (err error) {
	//初始化logrus的配置
	log.Formatter = &logrus.JSONFormatter{} //记录JSON格式的日志
	//指定日志输出
	file, err := os.OpenFile("./xx.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
	if err != nil {
		fmt.Println("open lofg file failed, err:", err)
		return
	}
	log.Out = file
	// 告诉Gin框架把它的日志也记录到我们打开的文件中
	gin.SetMode(gin.ReleaseMode) // 上线的时候要设置为ReleaseMode
	gin.DisableConsoleColor()
	gin.DefaultWriter = log.Out
	//设置日志级别
	log.Level = logrus.DebugLevel
	return
}

func loginHandler(c *gin.Context) {
	if c.Request.Method == "POST" {
		toPath := c.DefaultQuery("next", "/index")
		var u UserInfo
		//将http请求绑定在一个结构体变量上
		err := c.ShouldBind(&u)
		if err != nil {
			c.HTML(http.StatusOK, "login.html", gin.H{
				"err": "用户名或密码不能为空",
			})
			return
		}
		if u.Username == "guan" && u.Password == "123" {
			// 登陆成功
			// 1. 设置Cookie
			c.SetCookie("username", u.Username, 20, "/", "127.0.0.1", false, true)
			// 跳转到index页面
			c.Redirect(http.StatusMovedPermanently, toPath)
		} else {
			// 密码错误
			c.HTML(http.StatusOK, "login.html", gin.H{
				"err": "用户名或密码错误",
			})
			return
		}

	} else {
		c.HTML(http.StatusOK, "login.html", nil)
	}
}

func indexHandler(c *gin.Context) {
	c.HTML(http.StatusOK, "index.html", nil)
}

func homeHandler(c *gin.Context) {
	// 在返回页面之前要先校验是否存在username的Cookie
	// 获取Cookie
	username, err := c.Cookie("username")
	if err != nil {
		// 直接让跳转到登录页面
		c.Redirect(http.StatusMovedPermanently, "/login")
		return
	}
	c.HTML(http.StatusOK, "home.html", gin.H{
		"username": username,
	})
}

func main() {
	err := initLogrus()
	if err != nil {
		panic(err)
	}
	r := gin.Default()
	r.LoadHTMLGlob("templates/*")

	r.Any("/login", loginHandler)
	r.GET("/index", indexHandler)
	r.GET("/home", homeHandler)
	//中间件
	//r.GET("/vip", cookieMiddleware, vipHandler)

	r.Run()
}
